<template>
  <div class="my-shares-container">
    <div class="shares-header">
      <h3>我的分享列表</h3>
      <div class="shares-actions">
        <button class="refresh-btn" @click="fetchShares" :disabled="loading">
          {{ loading ? '加载中...' : '刷新' }}
        </button>
      </div>
    </div>
    
    <div v-if="loading" class="loading-indicator">
      正在加载分享列表...
    </div>
    
    <div v-else-if="error" class="error-message">
      {{ error }}
    </div>
    
    <div v-else-if="shares.length === 0" class="empty-shares">
      您还没有分享任何文件，请先在"个人文件"页面分享文件。
    </div>
    
    <div v-else class="shares-table-container">
      <table class="shares-table">
        <thead>
          <tr>
            <th>文件名</th>
            <th>大小</th>
            <th>分享时间</th>
            <th>访问量</th>
            <th>分享链接</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(share, index) in shares" :key="share.urlmd5">
            <td  >
                <div style="display: flex; align-items: center; gap: 8px;">
                    <div class="file-icon" :class="getFileIconClass(getFileExtension(share.file_name))"></div>
                    {{ share.file_name }}
                </div>
            </td>
            <td>{{ formatFileSize(share.size) }}</td>
            <td>{{ share.create_time }}</td>
            <td>{{ share.pv }}</td>
            <td class="share-link-cell">
              <div class="share-link-container">
                <input 
                  type="text" 
                  :value="generateShareLink(share.urlmd5)" 
                  readonly 
                  class="share-link-input" 
                  :ref="el => { if (el) shareInputRefs[share.urlmd5] = el }"
                />
                <button class="copy-btn" @click="copyShareLink(share.urlmd5)">
                  {{ copyStates[share.urlmd5] ? '已复制' : '复制' }}
                </button>
              </div>
            </td>
            <td >
              <button class="action-btn preview-btn" title="查看分享" @click="openShareView(share)">
                <span>👁️</span>
              </button>
              <button class="action-btn delete-btn" title="取消分享" @click="confirmDelete(share)" :disabled="isDeleting">
                <span>🗑️</span>
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      
      <div class="pagination">
        <span>总计 {{ total }} 个分享</span>
        <div class="pagination-controls">
          <button 
            :disabled="currentPage <= 1"
            @click="changePage(currentPage - 1)"
          >
            上一页
          </button>
          <span>{{ currentPage }} / {{ totalPages }}</span>
          <button 
            :disabled="currentPage >= totalPages"
            @click="changePage(currentPage + 1)"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
    
    <!-- 删除确认对话框 -->
    <div v-if="showDeleteConfirm" class="confirm-dialog-overlay">
      <div class="confirm-dialog">
        <h3>确认取消分享</h3>
        <p>您确定要取消分享文件 <strong>"{{ shareToDelete?.file_name }}"</strong> 吗？</p>
        <p class="warning-text">此操作不会删除文件本身，仅删除分享链接。</p>
        <div class="confirm-actions">
          <button 
            class="cancel-btn" 
            @click="cancelDelete" 
            :disabled="isDeleting"
          >
            取消
          </button>
          <button 
            class="delete-confirm-btn" 
            @click="deleteConfirmed" 
            :disabled="isDeleting"
          >
            {{ isDeleting ? '处理中...' : '确认取消分享' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();
const shares = ref([]);
const total = ref(0);
const loading = ref(false);
const error = ref('');
const currentPage = ref(1);
const pageSize = 10; // 每页显示的文件数量

// 复制相关状态
const shareInputRefs = reactive({});
const copyStates = reactive({});

// 删除确认对话框状态
const showDeleteConfirm = ref(false);
const shareToDelete = ref(null);
const isDeleting = ref(false);

// 计算总页数
const totalPages = computed(() => {
  return Math.max(1, Math.ceil(total.value / pageSize));
});

// 获取文件扩展名
const getFileExtension = (filename) => {
  return filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2).toLowerCase();
};

// 获取文件图标类
const getFileIconClass = (fileType) => {
  const typeMap = {
    'png': 'image-icon',
    'jpg': 'image-icon',
    'jpeg': 'image-icon',
    'gif': 'image-icon',
    'mp4': 'video-icon',
    'avi': 'video-icon',
    'mov': 'video-icon',
    'mp3': 'audio-icon',
    'wav': 'audio-icon',
    'pdf': 'pdf-icon',
    'doc': 'doc-icon',
    'docx': 'doc-icon',
    'xls': 'excel-icon',
    'xlsx': 'excel-icon',
    'txt': 'text-icon',
    'zip': 'archive-icon',
    'rar': 'archive-icon',
    'dll': 'binary-icon'
  };
  
  return typeMap[fileType] || 'file-icon';
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B';
  
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 生成分享链接
const generateShareLink = (urlmd5) => {
  return `${window.location.origin}/share?urlmd5=${urlmd5}`;
};

// 获取分享列表
const fetchShares = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    const token = localStorage.getItem('token');
    const user = localStorage.getItem('user');
    
    if (!token || !user) {
      error.value = '用户未登录或登录已过期';
      return;
    }
    
    const start = (currentPage.value - 1) * pageSize;
    
    // 构建请求数据
    const requestData = {
      count: pageSize,
      start: start,
      token: token,
      user: user
    };
    
    // 发送请求
    const response = await axios.post('/api/sharepic?cmd=normal', requestData, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    console.log('获取分享列表响应:', response.data);
    
    if (response.data.code === 0) {
      shares.value = response.data.files || [];
      total.value = response.data.total || 0;
    } else {
      error.value = response.data.message || '获取分享列表失败';
      console.error('获取分享列表失败:', response.data);
    }
  } catch (err) {
    console.error('获取分享列表请求错误:', err);
    error.value = '网络错误，请稍后重试';
  } finally {
    loading.value = false;
  }
};

// 复制分享链接
const copyShareLink = (urlmd5) => {
  const inputEl = shareInputRefs[urlmd5];
  if (!inputEl) return;
  
  // 选择输入框文本
  inputEl.select();
  inputEl.setSelectionRange(0, 99999);
  
  try {
    // 尝试使用document.execCommand API (兼容性更好)
    const success = document.execCommand('copy');
    if (success) {
      copyStates[urlmd5] = true;
      setTimeout(() => {
        copyStates[urlmd5] = false;
      }, 2000);
      showCenterNotification('分享链接已复制到剪贴板', 'success');
    } else {
      // 如果execCommand失败，尝试使用Clipboard API
      navigator.clipboard.writeText(generateShareLink(urlmd5))
        .then(() => {
          copyStates[urlmd5] = true;
          setTimeout(() => {
            copyStates[urlmd5] = false;
          }, 2000);
          showCenterNotification('分享链接已复制到剪贴板', 'success');
        })
        .catch(err => {
          console.error('复制失败:', err);
          showCenterNotification('复制失败，请手动复制', 'error');
        });
    }
  } catch (err) {
    console.error('复制出错:', err);
    showCenterNotification('复制失败，请手动复制', 'error');
  }
};

// 打开分享预览页面
const openShareView = (share) => {
  window.open(`/share?urlmd5=${share.urlmd5}`, '_blank');
};

// 切换页码
const changePage = (page) => {
  if (page < 1 || page > totalPages.value) return;
  currentPage.value = page;
  fetchShares();
};

// 删除相关函数
const confirmDelete = (share) => {
  shareToDelete.value = share;
  showDeleteConfirm.value = true;
};

const cancelDelete = () => {
  showDeleteConfirm.value = false;
  shareToDelete.value = null;
};

const deleteConfirmed = () => {
  if (shareToDelete.value) {
    deleteShare(shareToDelete.value);
  }
};

const deleteShare = async (share) => {
  try {
    isDeleting.value = true;
    const token = localStorage.getItem('token');
    const user = localStorage.getItem('user');
    
    if (!token || !user) {
      error.value = '用户未登录或登录已过期';
      showCenterNotification('用户未登录或登录已过期', 'error');
      return;
    }
    
    // 构建删除请求数据
    const deleteData = {
      user: user,
      token: token,
      urlmd5: share.urlmd5
    };
    
    // 发送删除请求
    const response = await axios.post('/api/sharepic?cmd=cancel', deleteData, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    console.log('取消分享响应:', response.data);
    
    if (response.data.code === 0) {
      // 取消分享成功
      showCenterNotification(`文件"${share.file_name}"已取消分享`, 'success');
      // 刷新分享列表
      fetchShares();
    } else {
      // 取消分享失败
      error.value = response.data.message || '取消分享失败';
      showCenterNotification(`取消分享失败: ${error.value}`, 'error');
      console.error('取消分享失败:', response.data);
    }
  } catch (err) {
    console.error('取消分享请求错误:', err);
    error.value = '网络错误，请稍后重试';
    showCenterNotification(`取消分享出错: ${error.value}`, 'error');
  } finally {
    isDeleting.value = false;
    showDeleteConfirm.value = false;
    shareToDelete.value = null;
  }
};

// 中央通知提示
const showCenterNotification = (message, type = 'success') => {
  // 创建一个通知元素
  const notificationElement = document.createElement('div');
  notificationElement.className = `center-notification ${type}`;
  
  // 设置内容
  notificationElement.innerHTML = `
    <div class="center-notification-content">
      <span class="center-notification-icon">${type === 'success' ? '✅' : '❌'}</span>
      <span class="center-notification-message">${message}</span>
    </div>
  `;
  
  // 添加到DOM
  document.body.appendChild(notificationElement);
  
  // 添加动画类
  setTimeout(() => {
    notificationElement.classList.add('show');
  }, 10);
  
  // 设置自动消失
  setTimeout(() => {
    notificationElement.classList.remove('show');
    notificationElement.classList.add('hide');
    
    // 动画结束后移除元素
    setTimeout(() => {
      if (document.body.contains(notificationElement)) {
        document.body.removeChild(notificationElement);
      }
    }, 300);
  }, 3000);
};

// 初始加载
onMounted(() => {
  fetchShares();
});
</script>

<style scoped>
.my-shares-container {
  width: 100%;
  height: 100%;
  overflow: auto;
  position: relative;
}

.shares-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.shares-header h3 {
  margin: 0;
  font-size: 18px;
}

.shares-actions {
  display: flex;
  gap: 10px;
}

.refresh-btn {
  padding: 8px 15px;
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.refresh-btn:hover {
  background-color: #e0e0e0;
}

.refresh-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.loading-indicator,
.error-message,
.empty-shares {
  padding: 30px;
  text-align: center;
  color: #666;
  background-color: #f9f9f9;
  border-radius: 4px;
  border: 1px solid #eee;
}

.error-message {
  color: #f44336;
}

.shares-table-container {
  width: 100%;
  overflow-x: auto;
}

.shares-table {
  width: 100%;
  border-collapse: collapse;
  background-color: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.shares-table th,
.shares-table td {
  text-align: left;
  padding: 10px 10px;
  border-bottom: 1px solid #eee;
}

.shares-table th {
  background-color: #f5f5f5;
  font-weight: 500;
  color: #333;
}

.shares-table tr:hover {
  background-color: #f9f9f9;
}

.file-icon {
  width: 20px;
  height: 20px;
  background-color: #ddd;
  border-radius: 2px;
}

.image-icon { background-color: #81c784; }
.video-icon { background-color: #64b5f6; }
.audio-icon { background-color: #9575cd; }
.pdf-icon { background-color: #e57373; }
.doc-icon { background-color: #4fc3f7; }
.excel-icon { background-color: #66bb6a; }
.text-icon { background-color: #9e9e9e; }
.archive-icon { background-color: #ffb74d; }
.binary-icon { background-color: #ba68c8; }
/* .file-icon { background-color: #9e9e9e; } */

.share-link-cell {
  max-width: 300px;
}

.share-link-container {
  display: flex;
  width: 100%;
}

.share-link-input {
  flex: 1;
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  font-size: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.copy-btn {
  padding: 6px 12px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  white-space: nowrap;
  font-size: 12px;
}

.copy-btn:hover {
  background-color: #45a049;
}

 

.action-btn {
  padding: 6px;
  background: none;
  border: none;
  cursor: pointer;
  border-radius: 4px;
}

.action-btn:hover {
  background-color: #f0f0f0;
}

.preview-btn {
  color: #2196f3;
}

.delete-btn {
  color: #f44336;
}

.action-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 10px 0;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination-controls button {
  padding: 5px 10px;
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.pagination-controls button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 确认对话框样式 */
.confirm-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.confirm-dialog {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  width: 400px;
  max-width: 90%;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.confirm-dialog h3 {
  margin-top: 0;
  color: #333;
}

.warning-text {
  color: #ff9800;
  font-weight: 500;
}

.confirm-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  gap: 10px;
}

.cancel-btn {
  padding: 8px 15px;
  background-color: #f5f5f5;
  color: #333;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.delete-confirm-btn {
  padding: 8px 15px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.delete-confirm-btn:hover {
  background-color: #d32f2f;
}

/* 中央通知样式 */
:global(.center-notification) {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%) translateY(-100%);
  z-index: 2000;
  min-width: 300px;
  max-width: 80%;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: transform 0.3s ease-out;
}

:global(.center-notification.show) {
  transform: translateX(-50%) translateY(0);
}

:global(.center-notification.hide) {
  transform: translateX(-50%) translateY(-100%);
}

:global(.center-notification-content) {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 4px;
}

:global(.center-notification.success .center-notification-content) {
  background-color: #e8f5e9;
  border-left: 4px solid #4caf50;
}

:global(.center-notification.error .center-notification-content) {
  background-color: #ffebee;
  border-left: 4px solid #f44336;
}

:global(.center-notification-icon) {
  margin-right: 10px;
}

:global(.center-notification-message) {
  color: #333;
}

@media (max-width: 768px) {
  .shares-table th:nth-child(3),
  .shares-table td:nth-child(3),
  .shares-table th:nth-child(4),
  .shares-table td:nth-child(4) {
    display: none;
  }
  
  .share-link-input {
    max-width: 120px;
  }
}
</style> 